package org.looom.orglooomschool.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import org.looom.orglooomschool.MainActivity15;

public class MusicService extends Service {

    private static final String TAG = "MusicService"; // 用于日志输出
    private MediaPlayer mediaPlayer;

    String resourceName = "music2"; // 要播放的音乐文件的名称，必须和 res/raw 下的文件名一致（不带扩展名）

    // Service 生命周期方法 onCreate()
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service Created");

        int resourceId = getResources().getIdentifier(resourceName, "raw", getPackageName());
        mediaPlayer = MediaPlayer.create(this, resourceId);
        mediaPlayer.setLooping(true);
        mediaPlayer.setVolume(1.0f, 1.0f); // 参数范围是 0.0f 到 1.0f
    }

    // 发送播放状态更新广播
    private void notifyPlaybackUpdate(String currentFilename) {
        Intent intent = new Intent(MainActivity15.ACTION_PLAYBACK_UPDATE);
        intent.putExtra(MainActivity15.EXTRA_FILENAME, currentFilename);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service Started, ID: " + startId);

        if (intent != null && intent.hasExtra("command")) {
            String command = intent.getStringExtra("command");
            if ("PLAY".equals(command)) {
                if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                    notifyPlaybackUpdate(resourceName);
                    Log.d(TAG, "Music Started");
                }
            } else if ("PAUSE".equals(command)) {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    Log.d(TAG, "Music Paused");
                }
            }
        }

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service Destroyed");
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
